from flask import Flask, request, render_template, jsonify
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
# 连接MySQL   协议：mysql+pymysql 用户名：root 密码：root IP地址：localhost 端口：3306 数据库名：flaskdb #这里的数据库需要提前建好
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:mdh123456@192.168.0.3:3306/industry4_django'
# 动态追踪数据库的修改. 性能不好. 且未来版本中会移除. 目前只是为了解决控制台的提示才写的
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
#创建数据库对象
db = SQLAlchemy(app)

class ApiRecordDamaLot(db.Model):
    __tablename__ = 'api_record_dama_lot'

    time = db.Column(db.INTEGER, nullable=False)
    lot = db.Column(db.String(100))
    model = db.Column(db.String(100))
    product_date = db.Column(db.String(100))
    quantity = db.Column(db.INTEGER)
    label = db.Column(db.String(200))
    id = db.Column(db.INTEGER, primary_key=True)

    def __init__(self, time, lot, model, product_date, quantity, label):
        self.time = time
        self.lot = lot
        self.model = model
        self.product_date = product_date
        self.quantity = quantity
        self.label = label


@app.route('/', methods=['GET', 'POST'])
def hello_world():
    dict_show = {'code': 200, 'msg': '上传成功'}  # 定义字典用于数据展示
    try:
        dataraw = request.get_json()
        print(dataraw, type(dataraw))
        # lot = ApiRecordDamaLot(1656490000, 'VB9B06', '3149VD', '20211210', 30988,
        #                      '[)>06PKD-VB9B06Q309881T3149VD21VLA1022224LVN16D20211210')
        lot = ApiRecordDamaLot(dataraw['time'], dataraw['lot'], dataraw['model'],
                               dataraw['product_date'], dataraw['quantity'], dataraw['label'])
        db.session.add(lot)  # 将记录插入到映射表中
        db.session.commit()
    except Exception as e:
        dict_show = {'code': 304, 'msg': '服务器处理异常'}
    return jsonify(dict_show)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5001)
# host='127.0.1.3',port=5555